'use strict';

const Controller = require('egg').Controller;

const jwt = require('jsonwebtoken');

class UserController extends Controller {
    //注册
  async registry() {
    //注册
    let {ctx,service} = this;
    let {username,password} = ctx.request.body;
    if(username && /\d{3,6}/.test(password)){
        //1.是否已经有此用户
        let target = await service.user.selectUser(username);
        if(target.length){
            //已经存在
            ctx.body = {
                code:4,
                msg:'此用户已注册'
            }
        }else{
            //不存在
            try{
                //1.加密
                let hmcPwd = ctx.helper.hmc(password);
                await service.user.registry(username,hmcPwd);
                ctx.body = {
                    code:1,
                    msg:'注册成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'参数有误'
        }
    }
  }

  //登录
  async login(){
    let {ctx,service} = this;
    let {username,password} = ctx.request.body;
    if(username && /\d{3,6}/.test(password)){
        //1.加密
        let hmcPwd = ctx.helper.hmc(password);
        
        let target = await service.user.login(username,hmcPwd);
        if(target.length){
            //生成令牌token
            let token = jwt.sign({username},'lixd',{expiresIn:60*60})  //1s 

            ctx.body = {
                code:1,
                msg:'登录成功',
                token
            }
        }else{
            ctx.body = {
                code:0,
                msg:'登录失败'
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'参数有误'
        }
    }
  }

  async detail(){
      console.log(this.ctx.params.id);
    this.ctx.body = "注册"
  }
}

module.exports = UserController

